<?php

class AlimentosController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Alimentos;

//        var_dump($_POST['Alimentos']);
//        die();
        if (isset($_POST['Alimentos'])) {
            $model->attributes = $_POST['Alimentos'];
            if ($model->save()) {
                $this->redirect(array('/../nutricion/valoresNutricionales/create', 'id_alimento' => $model->id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);


        if (isset($_POST['Alimentos'])) {
            $model->attributes = $_POST['Alimentos'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Alimentos');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Alimentos('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Alimentos']))
            $model->attributes = $_GET['Alimentos'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Alimentos::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'alimentos-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionContenidos() {
        $model = new Institucion;
        $this->render('contenidos'
                , array(
            'model' => $model,
                )
        );
    }

    public function actionBuscarValNutricional($idAlimento = null) {
        $valoresNutri = ValoresNutricionales::model()->de_alimento($idAlimento)->findAll();

        if (isset($valoresNutri)) {
            $compuestos = array_keys($valoresNutri[0]['oldValues']);
            $cantidad = array_values($valoresNutri[0]['oldValues']);
            unset($compuestos[0]);
            unset($compuestos[1]);
            $compuestos = array_values($compuestos);
            unset($cantidad[0]);
            unset($cantidad[1]);
            $cantidad = array_values($cantidad);
            $data = array_combine($compuestos, $cantidad);
            echo json_encode($data);
        }
    }

    public function actioncargarSubcategorias() {
        $categoria_id = $_POST['Alimentos']['categoria_id'];
//        var_dump($categoria_id);
//        die();
        $model = Subcategoria::model()->de_categoria_id($categoria_id)->findAll();
        $data = CHtml::listData($model, 'id', Subcategoria::representingColumn());
        echo CHtml::tag('option', array('value' => ''), ' -- Seleccione -- ', true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

    public function actionIngresarAlimentos($lista = null) {
        $alimentos = array();
        if ($lista != null) {
            $lista = substr($lista, 1, strlen($lista));
            $contenedor = explode(",", $lista);
            foreach ($contenedor as $value) {
                $alimento = Alimentos::model()->findByPk($value); 
                if(isset($alimento)!= ''){
                    array_push($alimentos, $alimento['oldValues']); 
                }
            }
             echo json_encode($alimentos);
        }
    }

}
